package com.ruoyi.exen.common.generator;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * 自定义主键策略
 * @author EMY2305005
 */
@Component
public class CustomIdGenerator implements IdentifierGenerator {

    @Autowired
    private SerialNoGenerator serialNoGenerator;

    private final Sequence sequence;

    public CustomIdGenerator() {
        this.sequence = new Sequence(null);
    }

    public CustomIdGenerator(InetAddress inetAddress) {
        this.sequence = new Sequence(inetAddress);
    }

    public CustomIdGenerator(long workerId, long dataCenterId) {
        this.sequence = new Sequence(workerId, dataCenterId);
    }

    public CustomIdGenerator(Sequence sequence) {
        this.sequence = sequence;
    }


    @Override
    public Number nextId(Object entity) {
        return sequence.nextId();
    }

    @Override
    public String nextUUID(Object entity) {
        //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
        String bizKey = entity.getClass().getName();
        StringBuilder prefix = new StringBuilder("QMS");
        if(bizKey.contains("8DApproval")){
            prefix.append("8DApproval");
        }else if(bizKey.contains("8D")){
            prefix.append("8D");
        } else if(bizKey.contains("Opl")){
            prefix.append("OPL");
        }else if(bizKey.contains("APQP")){
            prefix.append("APQP");
        }else if(bizKey.contains("ProjectFile")){
            prefix.append("PFile");
        } else if(bizKey.contains("File")){
            prefix.append("FILE");
        }else if(bizKey.contains("SPC")){
            prefix.append("SPC");
        }
        //根据bizKey调用分布式ID生成
        //返回生成的id值即可.
        String id = serialNoGenerator.generateSerialNo(prefix.toString());
        return id;
    }
}